package com.sf.trtms.trade.personal.utils;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

public class ValidationUtil {
	
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	
	public static <T> String validate(T t){
		return validate(t,false);
	}
	
	/**
	 * 
	 * @param t
	 * @param append 是否把所有错误信息拼起来， false只返回第一个错误
	 * @return
	 */
	public static <T> String validate(T t,boolean append){
		Set<ConstraintViolation<T>> set = validator.validate(t, Default.class);
    	if(!set.isEmpty()){
    		StringBuilder sb = new StringBuilder();
    		for(ConstraintViolation<T> cv : set){
    			if(append)
    				sb.append(cv.getMessage()).append(";");
    			else {
    				return cv.getMessage();
    			}
    		}
    		return sb.toString();
    	}
    	return null;
	}
}
